package main.java.indi.zyj.c150.greedy;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class _03_MergingInterval {


    public int[][] merge(int[][] intervals) {


//        Arrays.sort(intervals, new Comparator<int[]>() {
//            public int compare(int[] interval1, int[] interval2) {
//                return interval1[0] - interval2[0];
//            }
//        });

        Arrays.sort(intervals, (int[] interval1, int[] interval2) -> interval1[0] - interval2[0]);

        List<int []> merged = new ArrayList<int []>();

        for (int i = 0; i < intervals.length; i++) {

            int left = intervals[i][0];
            int right = intervals[i][1];
            if (merged.size() == 0 || merged.get(merged.size() - 1)[1] < left){
                merged.add(intervals[i]);
            }else {
                merged.get(merged.size() - 1)[1] = Math.max(right, merged.get(merged.size() - 1)[1]);
            }


        }
        return merged.toArray(new int[merged.size()][]);

    }


}
